import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AppLoggerService } from '../services/logger.service';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new AppLoggerService('HTTP');

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const response = context.switchToHttp().getResponse();
    const { method, url, body, user } = request;
    const startTime = Date.now();

    // 记录请求日志
    this.logger.apiRequest(method, url, body, user);

    return next.handle().pipe(
      tap({
        next: (data) => {
          const duration = Date.now() - startTime;
          const statusCode = response.statusCode;
          
          // 记录响应日志
          this.logger.apiResponse(method, url, statusCode, duration);
          
          // 如果是错误响应，记录详细信息
          if (statusCode >= 400) {
            this.logger.error(`API Error: ${method} ${url} - ${statusCode}`, undefined, 'HTTP');
            if (data && typeof data === 'object') {
              this.logger.debug(`Error Details: ${JSON.stringify(data)}`, 'HTTP');
            }
          }
        },
        error: (error) => {
          const duration = Date.now() - startTime;
          const statusCode = error.status || 500;
          
          // 记录错误响应日志
          this.logger.apiResponse(method, url, statusCode, duration);
          this.logger.error(`API Error: ${method} ${url} - ${error.message}`, error.stack, 'HTTP');
        },
      }),
    );
  }
}

